//
//  CourseDetailsViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/22.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CourseDetailsViewController.h"
#import "MakeSureTheOrderViewController.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "AgencyDetailsCollectionViewCell.h"
#import "AgencyVideoShowViewController.h"
#import "DrivateTutorDetailTableViewCell.h"
#import "SharePopView.h"

static NSString *collectionIdentifier = @"AgencyDetailsCollectionViewCell";
static NSString * CellIdentifier = @"DrivateTutorDetailTableViewCell";

@interface CourseDetailsViewController ()
<BestScrollViewDelegate,BestScrollViewDatasource,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,MWPhotoBrowserDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;

@property (strong, nonatomic) IBOutlet UIImageView *headerImage;//头像
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;//名字
@property (strong, nonatomic) IBOutlet UILabel *IntroductionLabel;//机构简介
@property (weak, nonatomic) IBOutlet UILabel *courseName;
@property (weak, nonatomic) IBOutlet UILabel *courseAddress;

@property (strong, nonatomic) IBOutlet UIView *CourseInformationView;//课程信息View
@property (strong, nonatomic) IBOutlet UILabel *CourseInformationLabel;//课程信息

@property (strong, nonatomic) IBOutlet UIView *AgencyShowView;//机构展示View
@property (strong, nonatomic) IBOutlet UICollectionView *collectView;


@property (strong, nonatomic) IBOutlet UIView *ApplicablePeopleView;//适用人群View
@property (strong, nonatomic) IBOutlet UILabel *ApplicablePeopleLabel;

@property (strong, nonatomic) IBOutlet UIView *evaluationView;//评价View
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *tableViewArray;

@property (strong, nonatomic) IBOutlet UIButton *BGbutton;
@property (strong, nonatomic) IBOutlet UIButton *collectionButton;
@property (strong, nonatomic) IBOutlet UIView *collectionView;//收藏View
@property (strong, nonatomic) IBOutlet UILabel *collectionLabel;

@property (strong, nonatomic) IBOutlet UIButton *collectionBack;

@property (strong, nonatomic) IBOutlet UILabel *PresentPriceLabel;//现价
@property (strong, nonatomic) IBOutlet UILabel *originalPriceLabel;//原价


@property (strong, nonatomic) NSDictionary *CourseDetailsDic;

@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property(nonatomic,strong)NSArray * showArray;

@property (strong, nonatomic) IBOutlet UIButton *unfoldButton;
@property (nonatomic,strong) NSString *mstoContent;

@property(nonatomic,strong)NSMutableArray * photos;
@property(nonatomic,strong)MWPhotoBrowser * browser;
@end

@implementation CourseDetailsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //状态栏文字颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    _photos = [NSMutableArray array];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    if (_backBlock) {
        _backBlock();
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _imageArray = [NSMutableArray array];
    _pageNO = 1;
    _tableViewArray = [NSMutableArray array];
    [self initViewLayout];
    [self CourseDetails];
    
    [self AgencyShow];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.collectionView];
    [self adaptiveViewLayout:self.scroview];
    _scroview.contentSize = flexibleSize(CGSizeMake(0, (_ApplicablePeopleView.frame.origin.y+_ApplicablePeopleView.frame.size.height)/VerticalRatio()), NO);
    [self adaptiveViewLayout:self.CourseInformationView];
    [self adaptiveViewLayout:self.AgencyShowView];
    [self adaptiveViewLayout:self.ApplicablePeopleView];

    self.collectionView.layer.cornerRadius = 5*VerticalRatio();
    self.collectionBack.layer.cornerRadius = 5*VerticalRatio();
    _headerImage.layer.masksToBounds = YES;
    _headerImage.layer.cornerRadius = 25*VerticalRatio();
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 177), NO)];
    [self.scroview insertSubview:_headerScroll belowSubview:_collectionButton];

    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    self.collectView.collectionViewLayout = flowLayout;
    
    
    [self.collectView registerNib:[UINib nibWithNibName:collectionIdentifier bundle:nil] forCellWithReuseIdentifier:collectionIdentifier];
    self.collectView.delegate = self;
    self.collectView.dataSource = self;
    self.collectView.backgroundColor = [UIColor whiteColor];
    
    [_tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    _browser = [[MWPhotoBrowser alloc] init];
    
    // Set options
    _browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
    _browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    _browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    _browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    _browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    _browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    _browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    
    // Optionally set the current visible photo before displaying
    // Manipulate
    [_browser showNextPhotoAnimated:YES];
    [_browser showPreviousPhotoAnimated:YES];

}

- (IBAction)back:(id)sender {
    [self backBtn];
   
}

#pragma mark - 查询机构展示
- (void)AgencyShow {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.mstoId forKey:@"mallStoreId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreExtendsList withHttpType:@"POST" withTag:JY_JY_mallStoreExtendsList];
}

#pragma mark - 展开
- (IBAction)developButton:(UIButton *)sender {
    if (!_unfoldButton.selected) {
        self.IntroductionLabel.text = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mallStore"][@"mstoContent"]];
        _IntroductionLabel.numberOfLines = 0;
        [_IntroductionLabel sizeToFit];
        _unfoldButton.frame = CGRectMake(_unfoldButton.frame.origin.x, _IntroductionLabel.frame.origin.y+_IntroductionLabel.frame.size.height+5, _unfoldButton.frame.size.width, _unfoldButton.frame.size.height);
        
        _CourseInformationView.frame = CGRectMake(_CourseInformationView.frame.origin.x, _unfoldButton.frame.origin.y+_unfoldButton.frame.size.height+10, _CourseInformationView.frame.size.width, _CourseInformationView.frame.size.height);
        
        _AgencyShowView.frame = CGRectMake(_AgencyShowView.frame.origin.x, _CourseInformationView.frame.origin.y+_CourseInformationView.frame.size.height, _AgencyShowView.frame.size.width, _AgencyShowView.frame.size.height);
        
        _ApplicablePeopleView.frame = CGRectMake(_ApplicablePeopleView.frame.origin.x, _AgencyShowView.frame.origin.y+_AgencyShowView.frame.size.height, _ApplicablePeopleView.frame.size.width, _ApplicablePeopleView.frame.size.height);
        
        _evaluationView.frame = CGRectMake(_evaluationView.frame.origin.x, _ApplicablePeopleView.frame.origin.y+_ApplicablePeopleView.frame.size.height, _evaluationView.frame.size.width, _evaluationView.frame.size.height);
    } else if (_unfoldButton.selected) {
        
        _IntroductionLabel.frame = flexibleFrame(CGRectMake(24, 291, 283, 54), NO);
        _IntroductionLabel.numberOfLines = 3;
        self.IntroductionLabel.text = [NSString stringWithFormat:@"%@…",_mstoContent];
        
        _unfoldButton.frame = flexibleFrame(CGRectMake(138, 343, _unfoldButton.frame.size.width/VerticalRatio(), _unfoldButton.frame.size.height/VerticalRatio()), NO);
        
        _CourseInformationView.frame = flexibleFrame(CGRectMake(0, 366, _CourseInformationView.frame.size.width/VerticalRatio(), _CourseInformationView.frame.size.height/VerticalRatio()), NO);
        
        _AgencyShowView.frame = flexibleFrame(CGRectMake(0, 490, _AgencyShowView.frame.size.width/VerticalRatio(), _AgencyShowView.frame.size.height/VerticalRatio()), NO);
        
        _ApplicablePeopleView.frame = flexibleFrame(CGRectMake(0, 627, _ApplicablePeopleView.frame.size.width/VerticalRatio(), _ApplicablePeopleView.frame.size.height/VerticalRatio()), NO);
    
        _evaluationView.frame = CGRectMake(0, 717*VerticalRatio(), _evaluationView.frame.size.width, _evaluationView.frame.size.height);
    }
    _scroview.contentSize = CGSizeMake(0, _evaluationView.frame.origin.y+_evaluationView.frame.size.height);
    sender.selected = !sender.selected;

}

#pragma mark - 取消收藏 && 取消分享
- (IBAction)cancel:(id)sender {
    _BGbutton.hidden = YES;
    _collectionView.hidden = YES;
}

#pragma mark - 分享
- (IBAction)sharebutton:(id)sender {
    
    SharePopView * popView = [[SharePopView alloc]initWithTitles:@[@"微信好友",@"朋友圈",@"QQ空间",@"QQ好友"] complect:^(NSInteger index) {
        if (index == 0) {
            //微信好友
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
            
        } else if (index == 1) {
            //朋友圈
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
            
            
        } else if (index == 2) {
            //QQ空间
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQzone] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
            
        } else if (index == 3) {
            //QQ好友
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
        }
        
    }];
    [popView show];
}

#pragma mark - 收藏
- (IBAction)collectionbutton:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    if (self.collectionButton.selected) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:self.mgooId forKey:@"mgooId"];

        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:JY_canleMallCollectGoods withHttpType:@"POST" withTag:JY_JY_canleMallCollectGoods];
    } else if (!self.collectionButton.selected) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:self.mgooId forKey:@"mgooId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:JY_mallCollectGoods withHttpType:@"POST" withTag:JY_JY_mallCollectGoods];
    }
}

#pragma mark - 支付
- (IBAction)pay:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
    MakeSureTheOrderViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MakeSureTheOrder"];
    
    page.courseDic = self.CourseDetailsDic;
    
    [[Common getNavigation] pushViewController:page];
}

#pragma mark - 查询课程详情
- (void)CourseDetails {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if ([Common getLoginStatus]) {
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    }
    [dic setObject:self.mgooId forKey:@"mgooId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallGoodsDetails withHttpType:@"POST" withTag:JY_JY_mallGoodsDetails];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroview.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self evaluation];
        });
        
    }];
    // 马上进入刷新状态
    [self.scroview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    
    if (_tableViewArray.count == _totle) {
        [self.scroview.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self evaluation];
        });
    }
    
}

#pragma mark - 查询课程评价
- (void)evaluation {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.mgooId forKey:@"mgcoGoodsId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallGoodsCommentLists withHttpType:@"POST" withTag:JY_JY_mallGoodsCommentLists];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableViewArray.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 108*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DrivateTutorDetailTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell= [[DrivateTutorDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    NSString *image = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"memberUser"][@"museImage"]];
    if (image && image.length>0 && ![self.tableViewArray[indexPath.row][@"memberUser"][@"mexpImage"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    cell.name.text = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"memberUser"][@"museNickName"]];
    cell.time.text = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"mgcoCreateTime"]];
    cell.detail.text = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"mgcoContent"]];
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 177), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index]]] placeholderImage:[UIImage imageNamed:@"school5"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
}
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _showArray.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(100*VerticalRatio(), 85*VerticalRatio());
    
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    AgencyDetailsCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionIdentifier forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    NSDictionary * dic= _showArray[indexPath.row];
    NSString * image = [NSString stringWithFormat:@"%@",dic[@"msexUrl"]];
    if (image.length>0) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    cell.videoImage.hidden = YES;
    NSString * type = [NSString stringWithFormat:@"%@",dic[@"msexType"]];
    if ([type isEqualToString:@"2"]) {
        cell.videoImage.hidden = NO;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic= _showArray[indexPath.row];
    NSString * type = [NSString stringWithFormat:@"%@",dic[@"msexType"]];
    if ([type isEqualToString:@"2"]) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
        AgencyVideoShowViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AgencyVideoShow"];
        page.videoId = [NSString stringWithFormat:@"%@",dic[@"msexId"]];
        [[Common getNavigation] pushViewController:page];
    }
    if ([type isEqualToString:@"1"]) {
        _browser.titleStr = @"机构展示";
        _browser.delegate = self;
        [_browser setCurrentPhotoIndex:0];
        // Present
        UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
        [self presentViewController:nc animated:YES completion:nil];
    }
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}

- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index{
    NSString * str = [NSString stringWithFormat:@"%ld/%ld",index+1,_photos.count];
    return str;
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroview.header endRefreshing];
    [_scroview.footer endRefreshing];
    if (tag==JY_JY_mallGoodsDetails) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.CourseDetailsDic = [NSDictionary dictionary];
            self.CourseDetailsDic = database[@"result"];
//
            NSString * images = [NSString stringWithFormat:@"%@",_CourseDetailsDic[@"mgooMultiImage"]];
            if (images.length>1) {
                images = [images substringToIndex:images.length-1];
            }
            
            self.imageArray = [[images componentsSeparatedByString:@","]mutableCopy];
            self.headerScroll.delegate=self;
            self.headerScroll.datasource=self;
            [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];

            
            NSString *isCollect = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"isCollect"]];
            if ([isCollect isEqualToString:@"1"]) {
                self.collectionButton.selected = YES;
            } else if ([isCollect isEqualToString:@"2"]) {
                self.collectionButton.selected = NO;
            }
            NSString *imageStr = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mgooImage"]];
            if (imageStr && imageStr.length>0 && ![self.CourseDetailsDic[@"mgooImage"] isEqual:[NSNull null]]) {
                [self.headerImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imageStr]]];
            }
            self.nameLabel.text = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mallStore"][@"mstoName"]];
            self.courseName.text = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mgooName"]];
            self.courseAddress.text = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mallStore"][@"mstoAddress"]];
            
            NSString *mstoContent = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mallStore"][@"mstoContent"]];
            if (mstoContent.length <= 65) {
                self.unfoldButton.hidden = YES;
                _IntroductionLabel.numberOfLines = 0;
                self.IntroductionLabel.text = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mallStore"][@"mstoContent"]];
                [_IntroductionLabel sizeToFit];
            } else if (mstoContent.length > 65) {
                self.unfoldButton.hidden = NO;
                
                NSString *string;
                for (int i = 64 ; i >= 0; i--) {
                    string =  [mstoContent substringWithRange:NSMakeRange(i,1)];
                    
                    NSString *str = @"，。、《》？；：’‘“”、|【】{}！@#￥%……&*（）-+=…";
                    
                    if (![str containsString:string]) {
                        _mstoContent = [mstoContent substringToIndex:i];
                        self.IntroductionLabel.text = [NSString stringWithFormat:@"%@…",_mstoContent];
                        break;
                    }
                }
            }

            
            
            _CourseInformationLabel.numberOfLines = 0;
            self.CourseInformationLabel.text = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mgooContext"]];
            [_CourseInformationLabel sizeToFit];
            self.PresentPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.CourseDetailsDic[@"mgooPrice"]];
            NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"原价￥%@",self.CourseDetailsDic[@"mgooOrigPrice"]]];
            [str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, str.length)];
            self.originalPriceLabel.attributedText = str;
            NSString *mstoMultiImage = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mgooMultiImage"]];
            NSArray * array = [mstoMultiImage componentsSeparatedByString:@","];
            for (int i = 1; i <= array.count; i++) {
                UIImageView *imageView;
                imageView.frame = flexibleFrame(CGRectMake(6+(i*101), 46, 95, 65), NO);
                NSString *imageStr;
                if (imageStr && imageStr.length>0 && ![array[i-1] isEqual:[NSNull null]]) {
                    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imageStr]]];
                    [self.AgencyShowView addSubview:imageView];
                }
                
            }
            
            NSString * Strs = [NSString stringWithFormat:@"%@",self.CourseDetailsDic[@"mgooAvaiClass"]];
            Strs = [Strs substringToIndex:Strs.length];
            NSArray *StrArray = [NSArray array];
            StrArray = [[Strs componentsSeparatedByString:@","]mutableCopy];
            _ApplicablePeopleLabel.numberOfLines = 0;
            NSString *mlsuNames = @"";
            for (int i = 0; i < StrArray.count; i++) {
                NSString *mlsuName = [NSString stringWithFormat:@"%@",StrArray[i]];
                mlsuNames = [NSString stringWithFormat:@"%@%d:%@;\n",mlsuNames,i+1,mlsuName];
            }
            _ApplicablePeopleLabel.text = mlsuNames;
            [_ApplicablePeopleLabel sizeToFit];
            _ApplicablePeopleView.frame = flexibleFrame(CGRectMake(_ApplicablePeopleView.frame.origin.x/VerticalRatio(), _ApplicablePeopleView.frame.origin.y/VerticalRatio(), _ApplicablePeopleView.frame.size.width/VerticalRatio(), _ApplicablePeopleLabel.frame.size.height/VerticalRatio()), NO);
            _scroview.contentSize = CGSizeMake(0, _ApplicablePeopleView.frame.origin.y+_ApplicablePeopleView.frame.size.height+20*VerticalRatio());
        }
        
            
    } else if (tag==JY_JY_mallCollectGoods) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.collectionLabel.text = @"收藏成功";
            _collectionView.hidden = NO;
            _BGbutton.hidden = NO;
            self.collectionButton.selected = YES;
        }
        
    } else if (tag==JY_JY_canleMallCollectGoods) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.collectionLabel.text = @"取消收藏";
            _collectionView.hidden = NO;
            _BGbutton.hidden = NO;
            self.collectionButton.selected = NO;
        }
        
    } else if (tag == JY_JY_mallStoreExtendsList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            _showArray = database[@"result"];
            for (int i = 0; i < _showArray.count; i++) {
                NSString *msexType = [NSString stringWithFormat:@"%@",_showArray[i][@"msexType"]];
                if ([msexType isEqualToString:@"1"]) {
                     NSString *url = [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_showArray[i][@"msexUrl"]];
                    MWPhoto * photo = [[MWPhoto alloc]initWithURL:[NSURL URLWithString:url]];
                    [_photos addObject:photo];
                }
            }
            [_collectView reloadData];
        }
    } else if (tag==JY_JY_mallGoodsCommentLists) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.scroview.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.scroview.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.tableViewArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.tableViewArray addObject:entity];
                }
                self.tableView.frame = flexibleFrame(CGRectMake(0, 37, 320, 108*self.tableViewArray.count), NO);
                self.evaluationView.frame = flexibleFrame(CGRectMake(0, 806, 320, 37+self.tableView.frame.size.height/VerticalRatio()), NO);
                _scroview.contentSize = flexibleSize(CGSizeMake(0, 806+self.evaluationView.frame.size.height/VerticalRatio()), NO);
                [self.tableView reloadData];
            });
           
        }
        
    }

}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_scroview.header endRefreshing];
    [_scroview.footer endRefreshing];    //
    [self dismissWaitDialog];
    
    
}
@end
